import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectEntityManager } from '@nestjs/typeorm';
import { EntityManager } from 'typeorm';
import { RegisterUserDto } from './dto/register-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { UserEntity } from './entities/user.entity';
import { PaginationQueryDto } from './dto/pagination-query';

@Injectable()
export class UserService {
  @InjectEntityManager()
  private readonly entityManager: EntityManager;

  async findAll({ current, pageSize }: PaginationQueryDto) {
    const pagesize = pageSize > 100 ? 100 : pageSize;

    const [users, total] = await this.entityManager.findAndCount(UserEntity, {
      select: ['id', 'nickname', 'created_at', 'username'],
      skip: (current - 1) * Number(pagesize),
      take: pagesize,
    });
    return {
      users,
      total,
    };
  }

  async update(id: number, { username }: UpdateUserDto) {
    const doc = await this.findOne(id);
    if (!doc) {
      throw new HttpException('用户未找到', HttpStatus.BAD_REQUEST);
    }

    await this.entityManager.update(
      UserEntity,
      { id },
      {
        username,
      },
    );
    return '修改成功';
  }

  async findOne(id: number) {
    const [user] = await this.entityManager.findBy(UserEntity, { id });
    return user;
  }

  async checkRegisterForm({
    username,
    password,
    passwordRepeat,
  }: RegisterUserDto) {
    if (password !== passwordRepeat) {
      throw new HttpException('两次输入的密码不一致', HttpStatus.BAD_REQUEST);
    }
    const [hasUser] = await this.entityManager.findBy(UserEntity, {
      username,
    });
    if (hasUser) {
      throw new HttpException('该手机号已注册', HttpStatus.BAD_REQUEST);
    }
  }

  async register(registerUserDto: RegisterUserDto) {
    await this.checkRegisterForm(registerUserDto);

    const user = this.entityManager.create(UserEntity, registerUserDto);
    this.entityManager.save(UserEntity, user);
    return '注册成功';
  }

  async remove(id: number) {
    const user = await this.findOne(id);
    if (!user) {
      throw new HttpException('该用户不存在或已删除', HttpStatus.BAD_REQUEST);
    }
    await this.entityManager.remove(UserEntity, user);
    return null;
  }
}
